package com.example.myserver;

import static android.content.ContentValues.TAG;

import android.app.Service;
import android.content.Intent;


import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service  {
    private int count;
    private boolean quit;
//    定义onBinder方法所返回的对象
//    通过继承来binder实现Ibindre类
    class MyBinder extends Binder {
//        获取service的运行状态
   public int getCount(){
       return MyService.this.count;
   }
}
    public MyService() {
    }
//Service被绑定的时候回调该方法
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("TAG", "onBind: ");
        return new MyBinder();
    }
//Service被创建时回调该方法
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "onCreate: ");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!quit){
                    try {
                        Thread.sleep(1000);
                        System.out.println(String.valueOf(count));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    MyService.this.count++;
                }
            }
        }).start();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d("TAG", "onStart: ");
    }

    //Servie被启动时回调该方法该方法在每次创建的时候都会执行
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }
//    Service 被关闭之前回调该方法

    @Override
    public boolean stopService(Intent name) {
        Log.d("TAG", "stopService: ");
        return super.stopService(name);
    }
//服务被断开时回调该方法
    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("TAG", "onUnbind: ");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy: ");
        this.quit =true;
    }
}